<?php

namespace App\Models;

use App\Models\Rbac\Role;
use DateTimeInterface;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Log;
use Laravel\Sanctum\HasApiTokens;
use Spatie\Permission\Traits\HasRoles;

class Admin extends Authenticatable
{
    use HasApiTokens, HasRoles;

    protected $fillable = [
        'username',
        'nickname',
        'email',
        'password',
        'avatar',
        'phone',
        'status',
        'register_ip'
    ];
    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array<int, string>
     */
    protected $hidden = [
        'password'
    ];

    /**
     * 关联的角色
     */
//    public function roles()
//    {
//        return $this->belongsToMany(Role::class, 'admin_roles');
//    }

    /**
     * 头像地址
     */
    protected function avatar(): Attribute
    {
        return Attribute::make(
            get: fn ($value) => asset($value ?? '/logo.png'),
            set: fn ($value) => normalizePath($value)
        );
    }

    /**
     * 加密密码
     */
    protected function password(): Attribute
    {
        return Attribute::make(
            set: fn ($value) => Hash::make($value),
        );
    }

    /**
     * 获取菜单
     */
    public function getMenuByRole($admin)
    {
        $admin->load('roles');
    }

    /**
     * 获取列表数据
     * @param $params
     */
    public static function getQueryData($params)
    {
        return self::query()->when($params['username'] ?? false, function ($query, $username) {
            return $query->where('username', $username);
        })->when($params['nickname'] ?? '' ,function ($query,$value){
            return $query->where('nickname','like',"%{$value}%");
        })->when($params['phone'] ?? '' ,function ($query,$value){
            return $query->where('phone','like',"%{$value}%");
        })->when($params['status'] ?? '' ,function ($query,$value){
            return $query->where('status',$value);
        })->with('roles:id,name,cn_name')
            ->paginate(request('pageSize',20));
    }

    /**
     * 格式化时间
     */
    protected function serializeDate(DateTimeInterface $date)
    {
        return $date->format('Y-m-d H:i:s');
    }
}
